package com.mgface.jersey.dao;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbutils.ResultSetHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mgface.jersey.core.DBUtilsTemplate;
import com.mgface.jersey.entity.User;

@Repository
public class UserDaoImpl implements UserDao {
	@Autowired
	private DBUtilsTemplate dbUtilsTemplate;

	@Override
	public User getUserInfo(String userId) throws SQLException {
		String sql = "select * from sj_user where userid=?";
		Object[] params = { userId };
		ResultSetHandler<User> rsh = new ResultSetHandler<User>() {

			@Override
			public User handle(ResultSet rs) {
				try {
					if (!rs.next()) {
						return null;
					}
					ResultSetMetaData meta = rs.getMetaData();
					User user = User.class.newInstance();
					Field[] fields = User.class.getDeclaredFields();
					Map<String, Field> resultMap = new HashMap<>();
					Arrays.asList(fields).parallelStream().forEach(u -> resultMap.put(u.getName().toUpperCase(), u));
					int count = meta.getColumnCount();
					for (int i = 0; i < count; i++) {
						String columnName = meta.getColumnName(i + 1).toUpperCase();
						Object value = rs.getObject(meta.getColumnName(i + 1));
						if (resultMap.containsKey(columnName)) {
							Field field = resultMap.get(columnName);
							field.setAccessible(true);
							field.set(user, value);
						}

					}
					return user;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		};
		return dbUtilsTemplate.get(sql, rsh, params);
	}

	@Override
	public int deleteUser(String userId) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int saveUser(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateUser(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

}
